﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace syc.Jidong
{
    public partial class 物料品种管理 : System.Web.UI.Page
    {
        protected string Notice = "";
        protected string Autorun = "";
        string sql = "SELECT ID,FID,品名,isnull(规格,'') as 规格,isnull(单位,'') as 单位,isnull(单价,0) as 单价,isnull(简码,'') as 简码,权重,大宗 FROM 物料品种";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.Date1.Text = DateTime.Today.ToLongDateString();
                string s = Request.QueryString["fid"];
                if (s == null)
                {
                    s = "";
                }
                int fid = 0;
                int.TryParse(s, out fid);
                this.Label_FID.Text = fid.ToString("D7");
                SetButtonState();
                this.SqlText.Text = sql;
                DateTime d1;
                if (!DateTime.TryParse(this.Date1.Text, out d1))
                {
                    d1 = DateTime.Today;
                }
                string sql2 = ";select @库存价值=sum(isnull(金额,0)) from 材料入出库 where 日期<='"+d1.ToShortDateString()+"'";
   
                if (fid == 0)
                {
                }
                else if (fid % 100000 == 0)
                {
                    this.SqlText.Text += " where fid>="+fid+" and fid<"+(fid+100000);
                    sql2 += " and 材料ID>=" + (fid*1000) + " and 材料ID<" + ((fid + 100000)*1000);
                }
                else if (fid % 1000 == 0)
                {
                    this.SqlText.Text += " where fid>=" + fid + " and fid<" + (fid + 1000);
                    sql2 += " and 材料ID>=" + (fid * 1000) + " and 材料ID<" + ((fid + 1000) * 1000);
                }
                else
                {
                    this.SqlText.Text += " where fid>=" + fid + " and fid<" + (fid + 1);
                    sql2 += " and 材料ID>=" + (fid * 1000) + " and 材料ID<" + ((fid + 1) * 1000);
                }

                this.SqlDataSource1.SelectCommand = this.SqlText.Text+sql2;
                
            }
            else
            {
                this.SqlDataSource1.SelectCommand = this.SqlText.Text;
            }
        }
        private void SetButtonState()
        {
            int fid = int.Parse(this.Label_FID.Text);
            this.Button_Ed.Enabled = true;
            this.Button_Del.Enabled = true;
            this.Button_Add.Enabled = true;
            if (fid == 0)
            {
                this.Button_Ed.Enabled = false;
                this.Button_Del.Enabled = false;
            }
            if (fid % 1000 > 0)
            {
                this.Button_Add.Enabled = false;
            }
        }

        protected void GridView1_DataBound(object sender, EventArgs e)
        {
            this.GridView1.SelectedIndex = -1;
            this.Button_Edit.Enabled = false;
            this.Button_Delete.Enabled = false;

            this.TextBox_Pager.Text = (this.GridView1.PageIndex + 1).ToString();
            this.Label_Pages.Text = " 共" + this.GridView1.PageCount.ToString() + "页 ";

            this.Button_Pager_First.CssClass = "pageturn-first-b";
            this.Button_Pager_First.Enabled = true;
            this.Button_Pager_Prev.CssClass = "pageturn-prev-b";
            this.Button_Pager_Prev.Enabled = true;
            this.Button_Pager_Next.CssClass = "pageturn-next-b";
            this.Button_Pager_Next.Enabled = true;
            this.Button_Pager_Last.CssClass = "pageturn-last-b";
            this.Button_Pager_Last.Enabled = true;
            if (this.GridView1.PageIndex == 0)
            {
                this.Button_Pager_Prev.CssClass = "pageturn-prev-g";
                this.Button_Pager_Prev.Enabled = false;
            }
            if (this.GridView1.PageIndex < 2)
            {
                this.Button_Pager_First.CssClass = "pageturn-first-g";
                this.Button_Pager_First.Enabled = false;
            }
            if (this.GridView1.PageIndex == this.GridView1.PageCount - 1 || this.GridView1.PageCount == 0)
            {
                this.Button_Pager_Next.CssClass = "pageturn-next-g";
                this.Button_Pager_Next.Enabled = false;

            }
            if (this.GridView1.PageIndex > this.GridView1.PageCount - 3)
            {
                this.Button_Pager_Last.CssClass = "pageturn-last-g";
                this.Button_Pager_Last.Enabled = false;
            }

        }
        protected void GridView1_PageIndexChanged(object sender, EventArgs e)
        {
            this.GridView1_DataBound(null, null);
        }
        protected void Pager_Click(object sender, EventArgs e)
        {
            if (sender.GetType().ToString() == "System.Web.UI.WebControls.Button")
            {
                switch (((Button)sender).CommandName)
                {
                    case "--":
                        this.GridView1.PageIndex = 0;
                        break;
                    case "-":
                        if (this.GridView1.PageIndex > 0) this.GridView1.PageIndex--;
                        break;
                    case "+":
                        if (this.GridView1.PageIndex < this.GridView1.PageCount - 1) this.GridView1.PageIndex++;
                        break;
                    case "++":
                        this.GridView1.PageIndex = this.GridView1.PageCount - 1;
                        break;
                }
            }
            else
            {

                int p;
                if (int.TryParse(TextBox_Pager.Text, out p))
                {
                    if (p >= 1 && p <= this.GridView1.PageCount)
                    {
                        this.GridView1.PageIndex = p - 1;
                    }
                }
                TextBox_Pager.Text = (this.GridView1.PageIndex + 1).ToString();
            }

        }
        protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
        {
            Label_Total.Text = "共查询到 " + e.AffectedRows + " 项记录";
            if (!Convert.IsDBNull(e.Command.Parameters[0].Value))
            {
                Label_Total.Text += " 库存价值：" + ((Double)e.Command.Parameters[0].Value).ToString("0.00")+"元";
            }
            else
            {
                Label_Total.Text += " 库存价值：0.00元";
            }
        }
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Button_Delete.Enabled = true;
            this.Button_Delete.CommandName = this.GridView1.SelectedDataKey[0].ToString();

            this.Button_Edit.Enabled = true;
            this.Button_Edit.OnClientClick = "parent.swin2_load('/Store/物料品种录入.aspx?id="
                + this.GridView1.SelectedDataKey[0].ToString() + "',560,300);return false;";
        }
        private string GetState()
        {
            string state = "";
            int id;
            if(int.TryParse(this.BianMa.Text,out id))
            {
                state += " and ID="+ id;
            }

            if (this.PinMing.Text != "")
            {
                state += " and 品名 like '%" + this.PinMing.Text.Replace("'", "") + "%'";
            }

            if (this.GuiGe.Text != "")
            {
                state += " and 规格 like '%" + this.GuiGe.Text.Replace("'", "") + "%'";
            }

            if (this.JianMa.Text != "")
            {
                state += " and 简码='" + this.JianMa.Text.Replace("'", "") + "'";
            }

            int qz=0;
            if (int.TryParse(this.QuanZhong.Text, out qz) && qz>0)
            {
                state += " and 权重="+qz;
            }
            if (state.StartsWith(" and"))
            {
                state = state.Substring(4);
            }
            if (state != "")
            {
                state = " where " + state;
            }
            return state;
        }
        protected void Button_Query_Click(object sender, EventArgs e)
        {
            if (this.Button_Mode.Text == "品种查询")
            {
                this.SqlDataSource1.SelectCommand = "";
                this.SqlDataSource1.SelectCommand = this.SqlText.Text;
                return;
            }
            string state = this.GetState();
            this.SqlText.Text = sql + state;
            this.SqlDataSource1.SelectCommand = "";
            this.SqlDataSource1.SelectCommand = this.SqlText.Text;
        }

        protected void Button_Reset_Click(object sender, EventArgs e)
        {
            this.PinMing.Text = "";
            this.GuiGe.Text = "";
            this.BianMa.Text = "";
            this.JianMa.Text = "";
            this.QuanZhong.Text = "";
        }

        protected void Button_Delete_Click(object sender, EventArgs e)
        {
            this.SqlDataSource1.DeleteParameters["ID"].DefaultValue = this.Button_Delete.CommandName;
            if (this.SqlDataSource1.Delete() > 0)
            {
                this.Notice = "·删除成功";
            }
            else
            {
                this.Notice = "·删除失败";
            }
        }

        protected void Button_Mode_Click(object sender, EventArgs e)
        {
            if (this.Button_Mode.Text == "品种查询")
            {
                this.Button_Mode.Text = "分类目录";
            }
            else
            {
                this.Button_Mode.Text = "品种查询";
            }
        }

        protected void Button_Del_Click(object sender, EventArgs e)
        {
            if (this.SqlDataSource2.Delete() > 0)
            {
                int fid = int.Parse(this.Label_FID.Text);
                if (fid % 100000 == 0)
                {
                    fid = 0;
                }
                else if (fid % 1000 == 0)
                {
                    fid = fid / 100000 * 100000;
                }
                else
                {
                    fid = fid / 1000 * 1000;
                }
                this.Label_FID.Text = fid.ToString("D7");
                this.Notice = "删除成功。";
                this.Autorun = "document.getElementById('" + int.Parse(this.Label_FID.Text).ToString("D7")
                            + "').firstChild.firstChild.firstChild.fireEvent('ondblclick')";
                SetButtonState();
            }
            else
            {
                this.Notice = "删除失败，请检查该分类是否有子分类，以及是否已包含的物料品种。";
            }
        }

        protected void Button_Export_Click(object sender, EventArgs e)
        {
            string part1 =
@"<html xmlns:o='urn:schemas-microsoft-com:office:office'
xmlns:x='urn:schemas-microsoft-com:office:excel'
xmlns='http://www.w3.org/TR/REC-html40'>
<head>
<meta http-equiv=Content-Type content='text/html; charset=utf-8'>
<style>
<!--table
@page
{mso-header-data:;
mso-footer-data:;
margin:.79in .31in .79in .31in;
mso-header-margin:.51in;
mso-footer-margin:.51in;
/*mso-page-orientation:landscape;*/
mso-horizontal-page-align:center;
}
-->
</style>
<!--[if gte mso 9]><xml>
 <x:ExcelWorkbook>
  <x:ExcelWorksheets>
   <x:ExcelWorksheet>
    <x:Name>物料品种编码</x:Name>
    <x:WorksheetOptions>
     <x:DefaultRowHeight>285</x:DefaultRowHeight>
     <x:Print>
      <x:ValidPrinterInfo/>
      <x:Scale>100</x:Scale>
      <x:PaperSizeIndex>9</x:PaperSizeIndex>
      <x:HorizontalResolution>200</x:HorizontalResolution>
      <x:VerticalResolution>200</x:VerticalResolution>
     </x:Print>
     <x:Selected/>
     <x:Panes>
      <x:Pane>
       <x:Number>3</x:Number>
       <x:ActiveRow>0</x:ActiveRow>
       <x:ActiveCol>0</x:ActiveCol>
      </x:Pane>
     </x:Panes>
    </x:WorksheetOptions>
   </x:ExcelWorksheet>
 </x:ExcelWorkbook>
</xml><![endif]-->
</head>
<body>
<style>
td{text-align:center;font-size:10pt;border:.5pt solid black;}
</style>
<table border=0 cellpadding=0 style=border-collapse:collapse>
<tr>
<td height=30 colspan=7 style=font-size:14pt;><b>物料品种编码</b></td>
</tr>
<tr>
<td width=100>编码</td>
<td width=150>品名</td>
<td width=120>型号/规格</td>
<td width=80>单位</td>
<td width=80>单价(元)</td>
<td width=80>简码</td>
<td width=60>权重</td>
</tr>";


            SqlConnection Conn = new SqlConnection();
            Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
            Conn.Open();
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.CommandText = this.SqlText.Text;
            SqlDataReader Reader = Cmd.ExecuteReader();

            Response.Charset = "utf-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-excel";
            Response.AddHeader("content-disposition", "attachment; filename=\"" + Server.UrlEncode("物料品种编码") + ".xls\"");

            Response.Write(part1);
            while (Reader.Read())
            {
                Response.Write("<tr><td style=\"mso-number-format:'\\@'\">"+((int)Reader["ID"]).ToString("D10")+"</td>");
                Response.Write("<td>" + (string)Reader["品名"] + "</td>");
                Response.Write("<td>" + (string)Reader["规格"] + "</td>");
                Response.Write("<td>" + (string)Reader["单位"] + "</td>");
                Response.Write("<td>" + ((decimal)Reader["单价"]).ToString() + "</td>");
                Response.Write("<td>" + (string)Reader["简码"] + "</td>");
                Response.Write("<td>" + ((int)Reader["权重"]).ToString() + "</td></tr>");
            }
            Reader.Close();
            Conn.Close();
            Reader.Dispose();
            Cmd.Dispose();
            Conn.Dispose();

            Response.Write("</table></body></html>");
            Response.End();
        }

        protected void Date1_TextChanged(object sender, EventArgs e)
        {
            int fid = 0;
            int.TryParse(this.Label_FID.Text, out fid);
            this.SqlText.Text = sql;
            DateTime d1;
            if (!DateTime.TryParse(this.Date1.Text, out d1))
            {
                d1 = DateTime.Today;
            }
            string sql2 = ";select @库存价值=sum(isnull(金额,0)) from 材料入出库 where 日期<='" + d1.ToShortDateString() + "'";

            if (fid == 0)
            {
            }
            else if (fid % 100000 == 0)
            {
                this.SqlText.Text += " where fid>=" + fid + " and fid<" + (fid + 100000);
                sql2 += " and 材料ID>=" + (fid * 1000) + " and 材料ID<" + ((fid + 100000) * 1000);
            }
            else if (fid % 1000 == 0)
            {
                this.SqlText.Text += " where fid>=" + fid + " and fid<" + (fid + 1000);
                sql2 += " and 材料ID>=" + (fid * 1000) + " and 材料ID<" + ((fid + 1000) * 1000);
            }
            else
            {
                this.SqlText.Text += " where fid>=" + fid + " and fid<" + (fid + 1);
                sql2 += " and 材料ID>=" + (fid * 1000) + " and 材料ID<" + ((fid + 1) * 1000);
            }

            this.SqlDataSource1.SelectCommand = this.SqlText.Text + sql2;
        }
    }
}
